package org.hgm.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.social.connect.Connection;
import org.springframework.social.google.api.Google;
import org.springframework.social.google.api.legacyprofile.LegacyGoogleProfile;
import org.springframework.social.google.connect.GoogleConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.GrantType;
import org.springframework.social.oauth2.OAuth2Operations;
import org.springframework.social.oauth2.OAuth2Parameters;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class GoogleController {
	GoogleConnectionFactory connectionFactory = new GoogleConnectionFactory("161859577480.apps.googleusercontent.com",
			"8BXOvc64m3L-jQuknwWk38dS");

	// GoogleConnectionFactory connectionFactory2 = new GoogleConnectionFactory("161859577480.apps.googleusercontent.com",
	// "8BXOvc64m3L-jQuknwWk38dS");

	@RequestMapping(value = "/g.htm", method = RequestMethod.GET)
	public void test(HttpServletResponse response) throws IOException {
		OAuth2Operations oauthOperations = connectionFactory.getOAuthOperations();
		OAuth2Parameters params = new OAuth2Parameters();
		params.setRedirectUri("http://localhost:8080/hgm/g2.htm");
		params.setScope("https://www.googleapis.com/auth/userinfo.profile");
		String authorizeUrl = oauthOperations.buildAuthorizeUrl(GrantType.AUTHORIZATION_CODE, params);
		response.sendRedirect(authorizeUrl);
	}

	@RequestMapping(value = "/g2.htm", method = RequestMethod.GET)
	public void test2(String code) throws IOException {
		OAuth2Operations oauthOperations = connectionFactory.getOAuthOperations();
		AccessGrant accessGrant = oauthOperations.exchangeForAccess(code, "http://localhost:8080/hgm/g2.htm", null);
		Connection<Google> connection = connectionFactory.createConnection(accessGrant);
		// connection.getApi().personOperations().getGoogleProfile();
		LegacyGoogleProfile userProfile = connection.getApi().userOperations().getUserProfile();
	}
}
